package com.taobao.tql.parser;

import java.io.StringReader;

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

public class TqlSelectParser {
	
	private TqlParserBean tqlParserBean = new TqlParserBean();
	public TqlSelectParser(String sql) {
		init(sql);
	}
	
	private void init(String sql) {
		CCJSqlParserManager pm = new CCJSqlParserManager();
		//String sql = "SELECT * FROM MY_TABLE1, MY_TABLE2, (SELECT * FROM MY_TABLE3) LEFT OUTER JOIN MY_TABLE4 "+
		//" WHERE ID = (SELECT MAX(ID) FROM MY_TABLE5) AND ID2 IN (SELECT * FROM MY_TABLE6)" ;
		
		//String sql = "SELECT aa,aa2,aa3,aa4 FROM MY_TABLE1, MY_TABLE2 where a = a" ;
		net.sf.jsqlparser.statement.Statement statement = null;
		try {
			statement = pm.parse(new StringReader(sql));
		} catch (JSQLParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			tqlParserBean.setException(e.getLocalizedMessage());
			return;
		}
		/* 
		now you should use a class that implements StatementVisitor to decide what to do
		based on the kind of the statement, that is SELECT or INSERT etc. but here we are only
		interested in SELECTS
		*/
		if (statement instanceof Select) {
			Select selectStatement = (Select) statement;
			PlainSelect plainSel = (PlainSelect) selectStatement.getSelectBody();
			
			if(plainSel.getWhere() != null)
			tqlParserBean.setWhere(String.valueOf(plainSel.getWhere()));
			if(plainSel.getFromItem() != null)
			tqlParserBean.setTabName(String.valueOf(plainSel.getFromItem()));
			if(plainSel.getSelectItems() != null)
			tqlParserBean.setFromItem(String.valueOf(plainSel.getSelectItems()));
		
		}
	}

	public TqlParserBean getTqlParserBean() {
		return tqlParserBean;
	}
}
